<?php
require_once(dirname(dirname(dirname(__FILE__))) . '/app.php');
require_once(dirname(__FILE__) . '/current.php');

need_manager();
need_auth('team');

$id = abs(intval($_GET['id']));
$team = $eteam = Table::Fetch('team', $id);
if($team && $team['proxy_id'] != $login_user['proxy_id']) die(include template('manage_misc_noright'));


/* 此处处理商家后台绑定的订单即时更新到新的商家 */
if( is_post()&& $team['partner_id'] != $_POST['partner_id'] ){ //判断是否改变了商家
	//将已产生绑定的商家ID的订单绑定到新的商家ID  注：仅允许订单类产品有此动作，本地服务类暂不支持
	$new_partner_id = $_POST['partner_id'];
	$map = array(
		'state' => 'pay',
		//'partner_id' => $team['partner_id'],
		'team_id' => $team['id'],
	);
	$orders = DB::LimitQuery('order', array( 'condition' => $map));
	if(count($orders) > 0){
		foreach ($orders as $order) {
			Table::UpdateCache('order', $order['id'], array(
				'partner_id' => $new_partner_id,
			));
		}
	}
}
/* 此处处理商家后台绑定的订单即时更新到新的商家 end */

if ( is_get() && empty($team) ) {
	$team = array();
	$team['id'] = 0;
	$team['user_id'] = $login_user_id;
	$team['begin_time'] = strtotime(date('Y-m-d', time()+86400));
	$team['end_time'] = strtotime('+2 days');
	$team['expire_time'] = strtotime('+3 months +1 days');
	$team['min_number'] = 1;
	$team['per_number'] = 0;
	$team['permin_number'] = 1;
	$team['market_price'] = 1;
	$team['team_price'] = 1;
	$team['delivery'] = 'coupon';
	$team['address'] = $profile['address'];
	$team['mobile'] = $profile['mobile'];
	$team['fare'] = 5;
	$team['farefree'] = 0;
	$team['bonus'] = abs(intval($INI['system']['invitecredit']));
	$team['conduser'] = $INI['system']['conduser'] ? 'Y' : 'N';
	$team['buyonce'] = 'N';
	$team['is_show_partner'] = 'Y';
	$team['is_show_api'] = 'Y';
}
else if ( is_post() ) {
	$team = $_POST;
	
	$insert = array(
	'title', 'short_title', 'market_price', 'team_price', 'end_time',
	'begin_time', 'expire_time', 'min_number', 'max_number',
	'summary', 'notice', 'per_number','permin_number','allowrefund', 'product','image', 'image1', 'image2', 'flv', 'now_number',
	'detail', 'userreview', 'card', 'systemreview',
	'conduser', 'buyonce', 'bonus', 'sort_order',
	'delivery', 'mobile', 'address', 'fare',
	'express', 'credit', 'farefree', 'pre_number',
	'user_id', 'city_id', 'group_id','sub_id', 'partner_id',
	'team_type', 'sort_order', 'farefree', 'state',
	'condbuy','express_relate','city_ids','is_show_partner','area_id','city_mode', 'batch_no', 'serv_code', 'proxy_id', 'audit_status', 'is_show_api',
	);
	$team['user_id'] = $login_user_id;
	$team['state'] = 'none';
	//if($team['audit_status'] == 1){
	    $team['begin_time'] = strtotime($team['begin_time']);
    	$team['end_time'] = strtotime($team['end_time']);
    	$team['expire_time'] = strtotime($team['expire_time']);
	//}
	$team['city_id'] = abs(intval($team['city_id']));
	$team['proxy_id'] = abs(intval($team['proxy_id']));
	$team['partner_id'] = abs(intval($team['partner_id']));
	$team['sort_order'] = abs(intval($team['sort_order']));
	$team['fare'] = abs(intval($team['fare']));
	$team['farefree'] = intval($team['farefree']);
	$team['pre_number'] = abs(intval($team['pre_number']));
//	if( $_FILES['upload_image']['name'] != '' ) {
//    	$team['image'] = upload_image('upload_image',null,'team',true);
//    	//$team['image1'] = upload_image('upload_image1',$eteam['image1'],'team');
//    	//$team['image2'] = upload_image('upload_image2',$eteam['image2'],'team');
//	}
    if($team['icon']){ //表单有上传图片动作
		$icon_pathinfo = pathinfo($team['icon']);
        $url_path = $icon_pathinfo['dirname'] . "/" . $icon_pathinfo['basename'];
        $team['image'] = strrchr($url_path, 'team');
	}
	//print_r($team);exit;
//print_r($team);exit;
	/* 城市模式单选或多选判断 */
	if ('more' == $team['city_mode']) {
		//echo 'asdf';exit;
		/* 序列化选取的城市 */
		if (!empty($team['city_ids'])) {
			if(in_array(0, $team['city_ids'])) {
				$team['city_id'] = 0; $team['city_ids'] = '@0@';
			}
			else {
				$team['city_id'] = abs(intval($team['city_ids'][0]));
				$team['city_ids'] = '@'.implode('@', $team['city_ids']).'@';
			}
		}else {
			Session::Set('notice', '请选择项目发布的城市');
			include template('manage_team_edit');
			return ;
		}
		$team['area_id'] = '0';
	}else{
		$team['city_id'] = $team['city_id_singel']; 
		$team['city_ids'] = '@'.$team['city_id'].'@';
		$team['area_id'] = intval($team['area_id']);
	}
	/* end 城市模式单选或多选判断 */
	
	if(empty($team['allowrefund']))  $team['allowrefund'] = 'N';
	if(empty($team['is_show_partner']))  $team['is_show_partner'] = 'N';
	if(empty($team['is_show_api']))  $team['is_show_api'] = 'N';

	/* 自定义快递价格 */
	$express_relate = $team['express_relate'];
	foreach ($express_relate as $k=>$v) {
		$e[$k]['id'] = $v;
		$e[$k]['price'] = $team["express_price_{$v}"];
	}
	$team['express_relate'] = serialize($e);

	//team_type == goods
	if($team['team_type'] == 'goods'){
		$team['min_number'] = 1;
		$team['conduser'] = 'N';
	}

	if ( !$id ) {
		$team['now_number'] = $team['pre_number'];
	} else {
		$field = strtoupper($table->conduser)=='Y' ? null : 'quantity';
		$now_number = Table::Count('order', array(
		'team_id' => $id,
		'state' => 'pay',
		), $field);
		$team['now_number'] = ($now_number + $team['pre_number']);

		/* 增加了总数，未卖完状态 */
		if ( $team['max_number'] > $team['now_number'] ) {
			$team['close_time'] = 0;
			$insert[] = 'close_time';
		}

		/* update coupon */
		DB::Update('coupon', array('team_id' => $id), array(
		'expire_time' => $team['expire_time'],
		'partner_id'  => $team['partner_id'],
		));
		/* update order */
		DB::Update('order', array('team_id' => $id), array(
		'allowrefund' => $team['allowrefund'],
		));
	}

	//dbx($team);
	$insert = array_unique($insert);
	$table = new Table('team', $team);
	$table->SetStrip('detail', 'systemreview', 'notice');

	if ( $team['id'] && $team['id'] == $id ) {
		$table->SetPk('id', $id);
		$table->update($insert);
		log_admin('team', '编辑team项目',$insert);
		Session::Set('notice', '编辑项目信息成功');
		redirect( WEB_ROOT . "/manage/team/index.php");
	}
	else if ( $team['id'] ) {
		log_admin('team', '非法编辑team项目',$insert);
		Session::Set('error', '非法编辑');
		redirect( WEB_ROOT . "/manage/team/index.php");
	}

	if ( $table->insert($insert) ) {
		log_admin('team', '新建team项目',$insert);
		Session::Set('notice', '新建项目成功');
		redirect( WEB_ROOT . "/manage/team/index.php");
	}
	else {
		log_admin('team', '编辑team项目失败',$insert);
		Session::Set('error', '编辑项目失败');
		redirect(null);
	}
}


$groups = DB::LimitQuery('category', array(
'condition' => array( 'zone' => 'group','fid' => '0', ),
));
$groups = Utility::OptionArray($groups, 'id', 'name');
/* 取得用户的分类 */
$user_group_ids = unserialize($auth_info['group_ids']);
foreach ($groups as $key => $val) {
	if (!in_array($key, $user_group_ids)) {
		unset($groups[$key]);
	}
}
/* 取得用户的分类 end */
$level_groups = DB::LimitQuery('category', array(
'condition' => array( "zone" => "group", " fid <> 0", ),
));
if($_GET['id']){
    $level_groups = DB::LimitQuery('category', array(
        'condition' => array( "zone" => "group", "fid" => $team['group_id'], ),
    ));
}

$level_groups = Utility::OptionArray($level_groups, 'id','name');

$partners = DB::LimitQuery('partner', array(
'condition' => array( 'proxy_id' => $login_user['proxy_id'] ),
'order' => 'ORDER BY id DESC',
));
$partners = Utility::OptionArray($partners, 'id', 'title');
$selector = $team['id'] ? 'edit' : 'create';

/* 快递公司信息 */
$express = db::LimitQuery('category',array(
'condition' => array( 'zone' => 'express', 'display'=>'Y', 'name' => '快递费用'),
'order'=>'ORDER BY sort_order DESC'
));
$relate = unserialize($team['express_relate']);
/* 合并订单快递和快递表快递数据 */
foreach ($relate as $k=>$v) {
	$ids[] = $v['id'];
	$data[$v['id']] = $v['price'];
}
foreach ($express as $k=>$v) {
	if (in_array($v['id'] , $ids)) {
		$express[$k]['relate_data'] = $data[$v['id']];
		$express[$k]['checked'] = 'checked';
	}
}

/* 反序列化城市信息 */
$city_ids = array_filter(explode('@', $team['city_ids']));

//查出所有城市
$citys = DB::LimitQuery('category', array(
	'condition' => array( 'zone' => 'city', 'display' => 'Y', 'id' => $auth_info['city_id'] ),'order' => 'ORDER BY `sort_order` DESC, `id` DESC',
));
//查出所有行政区域
$areas = DB::LimitQuery('area', array(
	'condition' => array( 'display' => 'Y', ),'order' => 'ORDER BY `sort_order` DESC, `id` DESC',
));
if($_GET['id']){
    $areas = DB::LimitQuery('area', array(
        'condition' => array( 'display' => 'Y', 'city_id' => $team['city_id'] ),'order' => 'ORDER BY `sort_order` DESC, `id` DESC',
    ));
}
include template('manage_team_edit');

